package org.iabako.client.ui.form.business.sale;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.config.page.PageEnum;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.tools.Messages;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.layout.field.*;
import org.iabako.client.ui.layout.template.Popup;
import org.iabako.client.ui.layout.widget.emailpreview.EmailForm;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.client.ui.page.business.sale.QuoteSearch;
import org.iabako.client.ui.page.business.sale.SaleSearch;
import org.iabako.client.user.AuthenticateUserProvider;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.business.Payment;
import org.iabako.shared.entity.business.Sale;
import org.iabako.shared.entity.enumeration.TrackingType;
import org.iabako.shared.entity.user.Enterprise;
import org.iabako.shared.iservice.business.PaymentServiceAsync;
import org.iabako.shared.iservice.function.InvoiceGeneratorServiceAsync;
import org.iabako.shared.tools.GenericTools;

import java.util.List;

/**
 * Created by jose on 12/03/15.
 */
public class SendInvoiceByEmail extends AbstractForm implements EmailForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, SendInvoiceByEmail> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    protected final InvoiceGeneratorServiceAsync invoiceGeneratorServiceAsync = InvoiceGeneratorServiceAsync.Util.getInstance();
    protected final PaymentServiceAsync paymentServiceAsync = PaymentServiceAsync.Util.getInstance();

    @UiField
    Button sendInvoiceByEmail;
    @UiField
    InputTextEmail email;
    @UiField
    InputTextArea body;
    @UiField
    LabelText seeCompleteMailVersion;
    @UiField
    InputText from;
    @UiField
    InputText subject;
    @UiField
    LabelText seeEmail;
    @UiField
    HTMLPanel emailContentPanel;
    @UiField
    LabelText title;

    Sale sale;
    Long idPayment;
    String invoiceNumber;
    boolean quoteMode;

    public SendInvoiceByEmail(Sale entity, Long idPay, String invoiceNum, boolean quoteMode) {
        sale = entity;
        this.idPayment = idPay;
        this.invoiceNumber = invoiceNum;
        this.quoteMode = quoteMode;

        simplePopup = true;
        setForm(binderForm, null, null);

        if (sale.getInvoiceRecipient() != null) {
            email.setValue(sale.getInvoiceRecipient().getEmail());
        } else if (sale.getClient() != null) {
            email.setValue(sale.getClient().getEmail());
        }

        if (this.quoteMode) {
            title.setLabel("quote_send_by_email");
        }

        setDefaultValues();
        setHandlers();
    }

    private void setDefaultValues() {
        Enterprise e = AuthenticateUserProvider.getUser().getEnterprise();
        final Enterprise enterprise = e.getParentEnterprise() != null ? e.getParentEnterprise() : e;
        final String name = sale.getInvoiceRecipient() != null ? sale.getInvoiceRecipient().getName() : sale.getClient() != null ? sale.getClient().getName() : "_no_client_";

        from.setValue(enterprise.getEmail());

        if (quoteMode) {
            subject.setValue(Messages.getLabel("quote_form_mail_subject", GenericTools.formatDate(sale.getDate())));
            body.setValue(Messages.getLabel("quote_form_mail_body",
                    name,
                    GenericTools.formatDate(sale.getDate()),
                    GenericTools.formatAmount(sale.calculateAmountFromProductsServices() + ""),
                    sale.getNumber(),
                    enterprise.getName()));
            body.setValue(body.getValue().replace(" " + "_no_client_", ""));
            sendInvoiceByEmail.setVisible(true);

        } else if (idPayment == null) {
            subject.setValue(Messages.getLabel("invoice_form_mail_subject", GenericTools.formatDate(sale.getDate())));
            body.setValue(Messages.getLabel("invoice_form_mail_body",
                    name,
                    GenericTools.formatDate(sale.getDate()),
                    GenericTools.formatAmount(sale.getRecalculatedTotal() + ""),
                    sale.getNumber(),
                    enterprise.getName()));
            sendInvoiceByEmail.setVisible(true);

        } else {
            paymentServiceAsync.getById(idPayment, new IabakoAsyncCallback<AbstractEntity>() {
                public void onSuccess(AbstractEntity entity) {
                    Payment payment = (Payment) entity;
                    subject.setValue(Messages.getLabel("receipt_form_mail_subject", GenericTools.formatDate(payment.getDate())));
                    body.setValue(Messages.getLabel("receipt_form_mail_body",
                            name,
                            GenericTools.formatDate(payment.getDate()),
                            GenericTools.formatAmount(payment.getAmount() + ""),
                            invoiceNumber,
                            enterprise.getName()));

                    sendInvoiceByEmail.setVisible(true);

                    super.onSuccess(entity);
                }
            });
        }
    }

    private void setHandlers() {
        seeEmail.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                emailContentPanel.setVisible(true);
                seeEmail.setVisible(false);
                Popup.mainLayoutDiv.setAttribute("style", Popup.mainLayoutDiv.getAttribute("style") + "; margin-top: 70px");
            }
        });

        sendInvoiceByEmail.getButton().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                if (GenericTools.isEmpty(email.getValue())) {
                    email.addErrorMessage(email, false, "invoice_form_recipient_email_error");
                    return;
                }
                if (!email.isValid()) {
                    email.addErrorMessage(email, false, "server_validation_email_pattern");
                    return;
                }

                if (quoteMode) {
                    invoiceGeneratorServiceAsync.sendQuoteByEmail(sale, sale.getProductsServices(), email.getValue(),
                            subject.getValue(), body.getValue(), new IabakoAsyncCallback<Void>() {
                        public void onSuccess(Void result) {
                            successCallback();
                            refreshQuoteSearch();
                            super.onSuccess(result);
                        }
                    });
                } else {
                    invoiceGeneratorServiceAsync.sendInvoiceByEmail(sale, idPayment, invoiceNumber, email.getValue(),
                            subject.getValue(), body.getValue(), new IabakoAsyncCallback<Void>() {
                        public void onSuccess(Void result) {
                            successCallback();
                            super.onSuccess(result);
                        }
                    });
                }
            }

            private void successCallback() {
                NavigationController.getInstance().closePopup(true);
                if (quoteMode) {
                    ValidationMessage.getFirstFromDOM().showSuccessMessage("quote_form_mail_sent");
                    AuthenticateUserProvider.getTrackingPanel().refresh(TrackingType.quoteSentByEmail);
                } else {
                    ValidationMessage.getFirstFromDOM().showSuccessMessage("invoice_form_mail_sent");
                    AuthenticateUserProvider.getTrackingPanel().refresh(TrackingType.invoiceSentByEmail);
                }
            }
        });

        final SendInvoiceByEmail parentForm = this;

        seeCompleteMailVersion.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                NavigationController.getInstance().closePopup(true);
                NavigationController.getInstance().goTo(PageEnum.EmailPreview, parentForm, null);
            }
        });
    }

    private void refreshQuoteSearch() {
        if (NavigationController.getInstance().getRootPage().pageContentComposite instanceof QuoteSearch) {
            //If rootPage is SaleSearch, we have to refresh search
            ((SaleSearch) NavigationController.getInstance().
                    getRootPage().pageContentComposite).saleSearchForm.searchForm.search(false);
        }
    }

    public String getFrom() {
        return Messages.getLabel("payment_request_mail_from") + " " + from.getValue();
    }

    public String getSubject() {
        return Messages.getLabel("payment_request_mail_subject_label") + " " + subject.getValue();
    }

    public String getBody() {
        return body.getValue().replace("\n", "<br/>");
    }

    public String getContentNote() {
        return null;
    }

    @Override
    protected List<IField> getMandatoryFields() {
        return null;
    }

    @Override
    protected AbstractEntity getEntity() {
        return null;
    }

    @Override
    public boolean validate() {
        return false;
    }
}
